<template>
  <div class="file-box">
    <!-- <q-btn flat icon="photo_camera"></q-btn> -->
    <!-- <div class="file-input">
      <input type="file" ref="file" @change="__add">
    </div> -->
    <div class="file-input">
      <!-- <q-icon :name="$q.icon.uploader.add"
        @click.native="__pick"
        class="q-uploader-pick-button q-if-control relative-position overflow-hidden">
      </q-icon> -->
      <q-btn flat dense :icon="$q.icon.uploader.add" :label="$t('选择')" @click.native="__pick" />
    </div>
    <!-- input file -->
    <input type="file" ref="file" class="hidden" @change="__add">
    <!-- 幻灯片过渡 -->
    <q-slide-transition>
      <q-list class="q-uploader-files q-py-none scroll file-list">
        <q-item v-if="fileList.length <= 0">
          <q-item-main :label="$t('还没有选择文件')" style="color: grey;"></q-item-main>
        </q-item>
        <q-item v-for="(file, idx) in fileList" :key="idx">
          <!-- icon or image -->
          <q-item-side v-if="file.__img" :image="file.__img.src"></q-item-side>
          <q-item-side v-else :icon="$q.icon.uploader.file" color="grey"></q-item-side>
          <!-- main content -->
          <q-item-main :label="file.name" :sublabel="file.__size"></q-item-main>
          <!-- delete icom -->
          <q-item-side right>
            <q-item-tile
              :icon="$q.icon.uploader[file.__doneUploading ? 'done' : 'clear']"
              color="negative"
              class="cursor-pointer"
              @click.native="__remove(file)"
            ></q-item-tile>
          </q-item-side>
        </q-item>
      </q-list>
    </q-slide-transition>
  </div>
</template>

<script>
import { humanStorageSize } from 'src/utils/index.js';
export default {
  data() {
    return {
      fileList: []
    }
  },
  methods: {
    __pick() {
      this.$refs.file.click();
    },
    __add(e, files) {
      let file = e.target.files[0];
      if(file){
        file.__size = humanStorageSize(file.size);
        // 判断是否为图片
        if(!file.type.toUpperCase().startsWith('IMAGE')){
          this.fileList.push(file);
        } else {
          const reader = new FileReader();
          let p = new Promise((resolve, reject) => {
            reader.onload = e => {
              let img = new Image();
              img.src = e.target.result;
              file.__img = img;
              resolve(true);
            }
            reader.onerror = e => { reject(e) }
          });
          reader.readAsDataURL(file);
          p.then(() => {
            this.fileList.push(file);
          });
        }
      }
      // 重置选择
      this.$refs.file.value = '';
      console.log(this.fileList);
    },
    __remove(file) {
      let name = file.name;
      this.fileList = this.fileList.filter(obj => obj.name !== name);
    },
    getFiles() {
      return this.fileList || [];
    }
  }
}
</script>

<style lang="less" scoped>
.file-box{
  .file-input{
    text-align: right;
  }
}
</style>

